<?php
require 'phpqrcode/qrlib.php';

// ��������� ������ �� �����
$configType = $_POST['configType'];
$number = $_POST['number'];
$ipType = $_POST['ipType'];
$ip = isset($_POST['ip']) ? $_POST['ip'] : ''; // ��������� IP-������

// ����������� � ���� ������ (���������, ��� ������ �����!)
$host = 'localhost';
$db = 'asterisk';
$user = 'freepbxuser';
$pass = '23f7e0274e9b27e18b0a243808a4df8e';

$dsn = "mysql:host=$host;dbname=$db";
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
    $stmt = $pdo->prepare("SELECT s.`id`, s.`data` AS `secret`, d.`description` FROM `sip` s LEFT JOIN `devices` d ON s.`id` = d.`id` WHERE s.`keyword` = 'secret' AND s.`id` = :id");
    $stmt->execute(['id' => $number]);
    $peer = $stmt->fetch();

    if (!$peer) {
        echo '������������ �� ������!';
        exit;
    }

    // ������������ $config 
    if ($configType === 'accountConfig') {
        $config = "<AccountConfig version='1'>
        <Account>
        <RegisterServer>{$ip}</RegisterServer>  
        <OutboundServer></OutboundServer> 
        <UserID>{$peer['id']}</UserID>  
        <AuthID>{$peer['id']}</AuthID> 
        <AuthPass>{$peer['secret']}</AuthPass> 
        <AccountName>{$peer['id']}</AccountName>  
        <DisplayName>{$peer['description']}</DisplayName> 
        <Dialplan>{x+|*x+|*++}</Dialplan>
        <RandomPort>0</RandomPort>
        <SecOutboundServer></SecOutboundServer>
        <Voicemail>*97</Voicemail>
        </Account>
        </AccountConfig>";
    } else {
        $config = json_encode([
            "name" => $peer['description'],
            "dn" => $ip, 
            "wdn" => $ip, 
            "ts" => [
                ["pn" => "TCP", "port" => "9526"],
                ["pn" => "TCP", "port" => "9526"]
            ],
            "ip" => $ip, 
            "private" => $ip, 
            "ext" => $peer['id'],
            "pwd" => $peer['secret'],
            "v" => 1
        ]);
    }

    // ��������� QR-����
    $filename = 'qr.png';
    QRcode::png($config, $filename, QR_ECLEVEL_L, 10);

    // �������� QR-���� � �������
    header('Cache-Control: no-cache, no-store, must-revalidate');
    header('Pragma: no-cache');

    echo '<img src="qr.png" />';
    echo '<a href="qr.png" download="qr.png">������� QR-���</a>';

} catch (PDOException $e) {
    echo 'Database error: ' . $e->getMessage();
    exit;
}
?>